package parasoft.centrap.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

public class ProgramText {

	/**
	 * @param args
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, InterruptedException {
			Process p = Runtime.getRuntime().exec(new String[]{"bash","export","XX=1234"});//,f.getAbsolutePath()});
			try {
				Vector vFile = new Vector();
				File file = new File("/etc/bashrc");
				if(file.exists()){
					BufferedReader inputReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
					String line = "";
					boolean found = false;
					while( (line = inputReader.readLine()) != null ){
							if( line.toUpperCase().indexOf("PARA_HOST")!=-1 ){
								found = true;
								line = "export PARA_HOST=127.0.0.1";
							}
						vFile.add(line);
					}
					if(!(found)){
						vFile.add("export PARA_HOST=127.0.0.1");
					}
					inputReader.close();

					BufferedWriter writer = new BufferedWriter(new FileWriter(file));
					for (Iterator iter = vFile.iterator(); iter.hasNext();) {
						line = (String) iter.next();
						writer.write(line);
						writer.newLine();
					}
					writer.close();
				}
			}
			catch(IOException e) {
				System.err.println("ERROR: " + e);
				return;
			}
			System.setProperty("PARA_HOST", "127.0.0.1");
			p = Runtime.getRuntime().exec(new String[]{"bash","source","./etc/bashrc"});//,f.getAbsolutePath()});
			p(p);
			p = Runtime.getRuntime().exec(new String[]{"printenv"});//,f.getAbsolutePath()});
		    p(p);
System.out.println();
System.out.println();
			Map m = null;//System.getenv();

			Set s = m.keySet();
			for (Iterator iterator = s.iterator(); iterator.hasNext();) {
				String object = (String) iterator.next();
				if(object.equals("PARA_HOST")){
					System.out.println(object+":"+m.get(object));
				}
			}
	}

public static void p(Process p) throws IOException{
		InputStream in = p.getInputStream();
	    int c;
	    StringBuffer sb = new StringBuffer();
	    while (((c = in.read()) != -1)&&((char)c!=' ')) {
	    	sb.append((char)c);
	    }
	    in.close();
	    System.out.println(sb);
	}
}


//InputStream is = process.getInputStream();
//InputStreamReader isr = new InputStreamReader(is);
//BufferedReader br = new BufferedReader(isr);
//String line;
//
//System.out.printf("Output of running %s is:", Arrays.toString(args));
//
//while ((line = br.readLine()) != null) {
//  System.out.println(line);
//}